import { onActivated, onMounted, onDeactivated, onBeforeUnmount, inject } from 'vue';
import { debounce } from 'lodash-es';
import type { AnimationPublish, CancelAnimationPublish } from '@/types/animationPublish';
import { useRoute } from 'vue-router';

/**
 * 缓存页面滚动位置
 * @param el String 节点名称
 * @param name String 缓存名称
 */
export const useCacheScrollTop = function (el = 'main', name = '') {
  const animationPublish = inject<AnimationPublish>('animationPublish');
  const cancelAnimationPublish = inject<CancelAnimationPublish>('cancelAnimationPublish');

  let scrollTop = 0;
  const storageName = 'mainScrollTop_' + name;
  const route = useRoute();
  // 监听滚动
  const scrollFn = debounce(function (e: Event) {
    scrollTop = (e.target as Element)?.scrollTop || 0;
  }, 80);
  onMounted(() => {
    const element = document.querySelector(el);
    if (element) {
      element.addEventListener('scroll', scrollFn);
    }
  });
  onBeforeUnmount(() => {
    cancelAnimationPublish && cancelAnimationPublish(name);
    const element = document.querySelector(el);
    element?.removeEventListener('scroll', scrollFn);
  });
  // 处理缓存
  onDeactivated(() => {
    sessionStorage.setItem(storageName, String(scrollTop || 0));
  });
  // 设置滚动条
  const setScrollTop = () => {
    const mainScrollTop = parseFloat(sessionStorage.getItem(storageName) || '0');
    const element = document.querySelector(el);
    if (mainScrollTop > 0 && element) {
      element.scrollTop = mainScrollTop;
    }
  };
  // 在合适的时机设置滚动条位置
  if (animationPublish) {
    // 为开启transition页面，需等动画结束设置滚动位置
    if (name) {
      animationPublish(name, () => {
        if (route.name === name) {
          setScrollTop();
        }
      });
    }
  } else {
    onActivated(() => {
      setScrollTop();
    });
  }
};
